#!/bin/bash

# TDengine Performance Test Script
set -e

echo "Starting TDengine performance tests..."

# Set variables
DB_HOST=${DB_HOST:-127.0.0.1}
RESULTS_DIR="/home/data/database/test_results"
mkdir -p $RESULTS_DIR

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
TDENGINE_RESULT_FILE="$RESULTS_DIR/tdengine_perf_$TIMESTAMP.log"

echo "TDengine Performance Test - $TIMESTAMP" > $TDENGINE_RESULT_FILE
echo "======================================" >> $TDENGINE_RESULT_FILE

# Test connection
echo "Testing connection to TDengine..." | tee -a $TDENGINE_RESULT_FILE
if ! docker exec tdengine-test taos -s "show databases;" > /dev/null 2>&1; then
  echo "Error: Could not connect to TDengine" | tee -a $TDENGINE_RESULT_FILE
  echo "Please check if TDengine is running and accessible." | tee -a $TDENGINE_RESULT_FILE
  exit 1
fi

echo "Great! Successfully connected to TDengine" | tee -a $TDENGINE_RESULT_FILE

# Test 1: Basic connection and version check
echo "1. Testing basic connection..." | tee -a $TDENGINE_RESULT_FILE
docker exec tdengine-test taos -s "show databases;" >> $TDENGINE_RESULT_FILE 2>&1
echo "Basic connection test completed" | tee -a $TDENGINE_RESULT_FILE

# Test 2: Create test database and tables
echo "2. Creating test database and tables..." | tee -a $TDENGINE_RESULT_FILE
docker exec tdengine-test taos -s "
CREATE DATABASE IF NOT EXISTS test;
USE test;
DROP TABLE IF EXISTS devices;
CREATE TABLE devices (
  ts TIMESTAMP,
  device_id NCHAR(32),
  temperature FLOAT,
  humidity FLOAT,
  pressure FLOAT,
  status TINYINT
) TAGS (location BINARY(64), type BINARY(32));
" >> $TDENGINE_RESULT_FILE 2>&1

echo "Database and table creation completed" | tee -a $TDENGINE_RESULT_FILE

# Test 3: Data insertion performance
echo "3. Testing data insertion performance..." | tee -a $TDENGINE_RESULT_FILE
START_TIME=$(date +%s.%N)

# Insert sample data (1000 records) - using batch insert for better performance
for i in $(seq 1 10); do
  BATCH_INSERT_SQL="USE test; INSERT INTO "
  for j in $(seq 1 100); do
    record_num=$(( (i-1)*100 + j ))
    BATCH_INSERT_SQL+="devices_$i USING devices TAGS ('Beijing', 'sensor') VALUES (NOW() + ${record_num}a, 'device_$record_num', $((20 + RANDOM % 10)).$((RANDOM % 100)), $((40 + RANDOM % 20)).$((RANDOM % 100)), $((1000 + RANDOM % 100)).$((RANDOM % 100)), $((RANDOM % 2))) "
  done
  docker exec tdengine-test taos -s "$BATCH_INSERT_SQL" >> $TDENGINE_RESULT_FILE 2>&1
done

END_TIME=$(date +%s.%N)
INSERT_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Insertion time for 1000 records: $INSERT_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Test 4: Query performance
echo "4. Testing query performance..." | tee -a $TDENGINE_RESULT_FILE

# Query 1: Simple COUNT
START_TIME=$(date +%s.%N)
docker exec tdengine-test taos -s "USE test; SELECT COUNT(*) FROM devices;" >> $TDENGINE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY1_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Count query time: $QUERY1_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Query 2: Conditional SELECT
START_TIME=$(date +%s.%N)
docker exec tdengine-test taos -s "USE test; SELECT * FROM devices WHERE temperature > 25 LIMIT 10;" >> $TDENGINE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY2_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Conditional query time: $QUERY2_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Query 3: Aggregation query
START_TIME=$(date +%s.%N)
docker exec tdengine-test taos -s "USE test; SELECT AVG(temperature), MAX(humidity), MIN(pressure) FROM devices;" >> $TDENGINE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY3_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Aggregation query time: $QUERY3_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Query 4: Time-range query
START_TIME=$(date +%s.%N)
docker exec tdengine-test taos -s "USE test; SELECT COUNT(*) FROM devices WHERE ts > NOW() - 1h;" >> $TDENGINE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
QUERY4_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Time-range query time: $QUERY4_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Test 5: Update performance (TDengine doesn't support traditional UPDATE, use tag update instead)
echo "5. Testing update performance..." | tee -a $TDENGINE_RESULT_FILE
START_TIME=$(date +%s.%N)
# For TDengine, we update tags instead of traditional UPDATE
docker exec tdengine-test taos -s "USE test; ALTER TABLE devices_1 SET TAG location = 'Shanghai';" >> $TDENGINE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
UPDATE_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Tag update time: $UPDATE_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Test 6: Complex analytical query
echo "6. Testing complex analytical query..." | tee -a $TDENGINE_RESULT_FILE
START_TIME=$(date +%s.%N)
docker exec tdengine-test taos -s "USE test; 
SELECT 
  location,
  COUNT(*) as device_count,
  AVG(temperature) as avg_temp,
  AVG(humidity) as avg_humidity
FROM devices 
GROUP BY location
INTERVAL(1h);" >> $TDENGINE_RESULT_FILE 2>&1
END_TIME=$(date +%s.%N)
COMPLEX_QUERY_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Complex analytical query time: $COMPLEX_QUERY_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Test 7: Concurrent query test
echo "7. Testing concurrent queries..." | tee -a $TDENGINE_RESULT_FILE
START_TIME=$(date +%s.%N)
for i in $(seq 1 5); do
  docker exec tdengine-test taos -s "USE test; SELECT COUNT(*) FROM devices WHERE device_id LIKE 'device_$(($i * 200))%';" >> $TDENGINE_RESULT_FILE 2>&1 &
done
wait
END_TIME=$(date +%s.%N)
CONCURRENT_TIME=$(echo "$END_TIME - $START_TIME" | bc)
echo "Concurrent query time: $CONCURRENT_TIME seconds" | tee -a $TDENGINE_RESULT_FILE

# Test 8: Resource usage
echo "8. Checking resource usage..." | tee -a $TDENGINE_RESULT_FILE
docker stats tdengine-test --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}" >> $TDENGINE_RESULT_FILE 2>&1

# Test 9: Database statistics
echo "9. Checking database statistics..." | tee -a $TDENGINE_RESULT_FILE
docker exec tdengine-test taos -s "USE test; SHOW TABLES;" >> $TDENGINE_RESULT_FILE 2>&1

# Summary
echo "" >> $TDENGINE_RESULT_FILE
echo "Performance Test Summary" >> $TDENGINE_RESULT_FILE
echo "=======================" >> $TDENGINE_RESULT_FILE
echo "Insertion Performance: $INSERT_TIME seconds for 1000 records" >> $TDENGINE_RESULT_FILE
echo "Count Query: $QUERY1_TIME seconds" >> $TDENGINE_RESULT_FILE
echo "Conditional Query: $QUERY2_TIME seconds" >> $TDENGINE_RESULT_FILE
echo "Aggregation Query: $QUERY3_TIME seconds" >> $TDENGINE_RESULT_FILE
echo "Time-range Query: $QUERY4_TIME seconds" >> $TDENGINE_RESULT_FILE
echo "Update Performance: $UPDATE_TIME seconds" >> $TDENGINE_RESULT_FILE
echo "Complex Analytical Query: $COMPLEX_QUERY_TIME seconds" >> $TDENGINE_RESULT_FILE
echo "Concurrent Queries: $CONCURRENT_TIME seconds for 5 queries" >> $TDENGINE_RESULT_FILE
echo "Test completed at: $(date)" >> $TDENGINE_RESULT_FILE

echo ""
echo "TDengine performance test completed!"
echo "Results saved to: $TDENGINE_RESULT_FILE"